package com.itheima.mm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mm.dto.R;
import com.itheima.mm.pojo.PageResult;
import com.itheima.mm.pojo.subject_manage.Subjects;
import com.itheima.mm.pojo.subject_manage.Tags;
import com.itheima.mm.service.SubjectsService;
import com.itheima.mm.service.TagsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/tags")
public class TagsController {
    @Autowired
    private TagsService tagsService;
    @Autowired
    private SubjectsService subjectsService;
    //标签添加
    @PostMapping
    public R addTags(@RequestBody Tags tags){
        tags.setCreatorId(1);
        tags.setSubjectId("1");
        tags.setAddDate(LocalDateTime.now());
        tagsService.save(tags);
        R r=new R();
        LambdaQueryWrapper<Tags> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Tags::getTagName,tags.getTagName());
        r.setId(tagsService.getOne(wrapper).getId());
        return r;
    }
    //标签修改
    @PutMapping("/{id}")
    public R modify(@RequestBody Tags tags){
        tagsService.updateById(tags);
        R r=new R();
        r.setSuccess(true);
        return r;
    }
    //标签列表
    @GetMapping
    public PageResult page(String tagName,Integer state,Integer page,Integer pagesize){
        LambdaQueryWrapper<Tags> wrapper=new LambdaQueryWrapper<>();
        if (tagName!=null)
            wrapper.like(Tags::getTagName,tagName);
        if (state!=null)
            wrapper.eq(Tags::getState,state);
        IPage<Tags> p=new Page<>(page,pagesize);
        IPage<Tags> pg = tagsService.page(p, wrapper);
        return new PageResult(pg.getTotal(),pg.getSize(),pg.getPages(),pg.getCurrent(),pg.getRecords());
    }
    //标签删除
    @DeleteMapping("/{id}")
    public R del(@PathVariable Integer id,@RequestBody Tags tags){
    tagsService.removeById(id);
    R r=new R();
    r.setSuccess(true);
    return r;
    }

    //标签状态
    @PostMapping("/{id}/{state}")
    public R tagState(@PathVariable Integer id,@PathVariable Integer state){
        Tags tags=new Tags();
        tags.setId(id);
        tags.setState(state);
        tagsService.updateById(tags);
        R r=new R();
        r.setSuccess(true);
        return r;
    }

    //标签详情
    @GetMapping("/{id}")
    public Tags findById(@PathVariable Integer id){
        Tags tag = tagsService.getById(id);
        Subjects subject = subjectsService.getById(tag.getSubjectId());
        tag.setSubjectName(subject.getSubjectName());
        return tag;
    }
}
